package com.hzdaba.aiapi.handlerInterceptor;

import com.hzdaba.aiapi.properties.TokenKeyProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 校验 token
 *
 * @author 刘逸晖
 */
@Component
public class CheckTokenHandlerInterceptor implements HandlerInterceptor {

    /**
     * 访问 Redis
     */
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * token key 相关的配置值
     */
    @Autowired
    private TokenKeyProperties tokenKeyProperties;

    /**
     * token 在请求头中的名称
     */
    @Value("${aiapi.aicustomer.token.all.request.header.name}")
    private String nameOfToken;

    /**
     * 请求中存放错误信息的 key
     */
    @Value("${aiapi.request.attribute.error.key}")
    private String keyOfError;

    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CheckTokenHandlerInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(this.nameOfToken);

        if (token == null || token.length() == 0) {
            response.setStatus(403);
            request.setAttribute(this.keyOfError, "请先登录，携带 token 访问");
            request.getRequestDispatcher("/error/error").forward(request, response);

//            CheckTokenHandlerInterceptor.logger.info("没有携带 token ，不予放行");
            return false;
        }

        Integer idOfCustomer = (Integer) this.redisTemplate.opsForHash().get(this.tokenKeyProperties.getPrefix(), token);

        if (idOfCustomer == null) {//token 不存在
            response.setStatus(403);
            request.setAttribute(this.keyOfError, "，抱歉，携带的 token 无效");
            request.getRequestDispatcher("/error/error").forward(request, response);

//            CheckTokenHandlerInterceptor.logger.info("token 不存在，不予放行");
            return false;
        }

        request.setAttribute("idOfCustomer", idOfCustomer);
        return idOfCustomer != null;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
